package com.travel.server.manager.impl.command.user;

import com.travel.common.util.CommonUtil;
import com.travel.server.manager.dto.request.user.UpdatePermissionRequest;
import com.travel.server.manager.dto.response.EmptyResponse;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.DepartmentDal;
import com.travel.server.manager.impl.dal.DepartmentMenuDal;
import com.travel.server.manager.model.DepartmentMenu;
import com.travel.server.manager.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author: LiZhenhui
 * @Date: 2018/11/20 17:13
 * @Desc:
 */
@Component
@Slf4j
public class UpdatePermissionCommand extends AbstractCommand<UpdatePermissionRequest, EmptyResponse> {

    @Autowired
    private DepartmentMenuDal departmentMenuDal;

    @Autowired
    private DepartmentDal departmentDal;

    @Override
    protected void checkInput(UpdatePermissionRequest request) {
        if(request.getId() == null){
            throwInvalidParam();
        }
    }

    @Override
    public EmptyResponse handle(UpdatePermissionRequest request) {
        UserInfo userInfo = getUserInfo();
        Date now = new Date();
        checkInput(request);
        departmentDal.selectById(request.getId());

        departmentMenuDal.deleteAllPermission(request.getId());
        if(StringUtils.isNotBlank(request.getMenuIdList())){
            List<Integer> menuIdList = CommonUtil.idsToList(request.getMenuIdList());
            Set<Integer> menuSet = new HashSet<>();
            for(Integer menuId : menuIdList){
                if(menuSet.add(menuId)) {
                    DepartmentMenu departmentMenu = new DepartmentMenu();
                    departmentMenu.setCreateBy(userInfo.getName());
                    departmentMenu.setCreateTime(now);
                    departmentMenu.setUpdateTime(now);
                    departmentMenu.setUpdateBy(userInfo.getName());
                    departmentMenu.setDepartmentId(request.getId());
                    departmentMenu.setMenuId(menuId);
                    departmentMenuDal.insertOrUpdate(departmentMenu);
                }
            }
        }
        return new EmptyResponse();
    }
}
